<template>
  <ContentWrap>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">基础信息</div>
      </div>
      <div class="content_main">
        <el-form 
          ref="formRef" 
          :inline="true" 
          :model="formData.data" 
          :rules="formRules" 
          class="-mb-15px"
          label-width="auto"
        >
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="预案名称" prop="name">
                <el-input class="formInp" v-model="formData.data.name" clearable placeholder="请输入预案名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预案类型" prop="type">
                <el-select class="formInp" v-model="formData.data.type" clearable placeholder="请选择预案类型">
                  <el-option v-for="item in filingTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编制部门" prop="departmentId">
                <el-tree-select
                  class="formInp"
                  v-model="formData.data.departmentId"
                  :data="deptTree"
                  filterable
                  clearable
                  :props="defaultProps"
                  check-strictly
                  default-expand-all
                  placeholder="请选择编制部门"
                  value-key="deptId"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编制时间" prop="emergencyTime">
                <el-date-picker
                  v-model="formData.data.emergencyTime"
                  style="width: 100%"
                  type="date"
                  placeholder="请选择编制时间"
                  @change="e => formData.data.emergencyTime = formatDateToYMD(e)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编制依据" prop="accordingId">
                <el-select class="formInp" v-model="formData.data.accordingId" clearable placeholder="请选择编制依据">
                  <el-option v-for="item in preparationList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select class="formInp" v-model="formData.data.status" clearable placeholder="请选择状态">
                  <el-option label="禁用" :value="0" />
                  <el-option label="启用" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预案简述" prop="remark">
                <el-input
                  v-model="formData.data.remark"
                  type="textarea"
                  maxlength="200"
                  :autosize="{ minRows: 6}"
                  placeholder="请输入预案简述信息"
                />
                <div class="formInp flex-e font-12" style="color: #999;">{{ formData.data.remark.length }}/200</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上传附件" prop="attachment">
                <div class="upload_box" style="width: 100%;">
                  <UploadFile
                    v-model="formData.data.attachment"
                    class="upload-demo"
                    :fileSize="20"
                    :fileType="['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']"
                    :limit="10"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </ContentWrap>
  <ContentWrap>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">应急工作组</div>
      </div>
      <div class="content_main">
        <el-row class="-mb-15px" :gutter="24">
          <el-col :span="24">
            <el-form-item label="指挥部：">
                <el-table :data="formData.data.commandList">
                  <template v-for="item in commandColumn" :key="item.prop">
                    <el-table-column
                      :width="item.width"
                      :align="item.align ? item.align : 'center'" 
                      :label="item.label"
                      :prop="item.prop"
                    >
                      <template #default="scope">
                        <div v-if="item.prop === 'position'">
                          <span v-if="scope.row.position && scope.row.position.length > 0">{{ scope.row.position.join('/') }}</span>
                          <span v-else>-</span>
                        </div>
                        <div v-else-if="item.prop === 'departmentId'">
                          {{ findDeptNameById(deptTree, scope.row.departmentId) || '-' }}
                        </div>
                        <div v-else>{{ scope.row[item.prop] || '-' }}</div>
                      </template>
                    </el-table-column>
                  </template>
            
                  <el-table-column :width="160" align="center" label="操作">
                    <template #default="scope">
                      <el-button link type="primary" @click="addCompanies(1, scope.row.commandName, scope.$index)">
                        编辑
                      </el-button>
                    </template>
                  </el-table-column>
            
                </el-table>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt-24">
            <el-form-item label="小组成员：">
              <el-table :data="formData.data.teamList">
                <template v-for="item in personalColumn" :key="item.prop">
                  <el-table-column
                    :width="item.width"
                    :align="item.align ? item.align : 'center'" 
                    :label="item.label"
                    :prop="item.prop"
                  >
                    <template #default="scope">
                      <div v-if="item.prop === 'position'">
                        <span v-if="scope.row.position && scope.row.position.length > 0">{{ scope.row.position.join('/') }}</span>
                        <span v-else>-</span>
                      </div>
                      <div v-else-if="item.prop === 'departmentId'">{{ scope.row.departmentId ? findDeptNameById(deptTree, scope.row.departmentId) : '-' }}</div>
                      <div v-else>{{ scope.row[item.prop] ? scope.row[item.prop] : '-' }}</div>
                    </template>
                  </el-table-column>
                </template>
          
                <el-table-column :width="100" align="center" label="操作">
                  <template #default="scope">
                    <el-button link type="danger" @click="companiesDel(scope.$index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
          
              </el-table>
              <el-button class="addRow" @click="addCompanies(2, '小组成员')" plain>
                <el-icon class="mr-6"><Plus /></el-icon>  添加
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt-24">
            <el-form-item label="主要职责：" prop="responsibility">
              <el-input 
                v-model="formData.data.responsibility" 
                class="formInp" 
                type="textarea"
                maxlength="200"
                :autosize="{ minRows: 6}"
                placeholder="请输入主要职责" 
              />
              <div class="formInp flex-e font-12" style="color: #999;">{{ formData.data.responsibility.length }}/200</div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
  </ContentWrap>
  <ContentWrap class="flex-c">
    <el-button class="!w-80px" type="primary" :loading="loading" @click="submitForm">确定</el-button>
    <el-button class="!w-80px" type="warning" @click="closeForm">取消</el-button>
  </ContentWrap>





  <personalDialog ref="personalDialogRef" @change="personalChange"/>
</template>
<script setup>
  import {ref,reactive} from "vue"
  import { Plus } from '@element-plus/icons-vue'
  import { formRules, personalColumn, commandColumn } from './jsonAndRules'
  import { formatDateToYMD } from '@/utils/index'
  import { defaultProps } from '@/utils/tree'
  import { UploadImgs, UploadFile } from "@/components/UploadFile/index.ts"
  import personalDialog from './personalDialog.vue'
  const filingTypeList = inject('filingTypeList')
  const preparationList = inject('preparationList')
  const findDeptNameById = inject('findDeptNameById')
  const goBack = inject('goBack', () => {})
  const deptTree = inject('deptTree')
  const personalDialogRef = ref(null)
  const message = useMessage() // 消息弹窗
  const loading = ref(false) // 列表的加载中
  const formRef = ref(null)
  const formData = reactive({
    data: {
      name: '', // 预案名称
      type: '', // 预案类型
      departmentId: '', // 编制部门
      emergencyTime: '', // 编制时间
      accordingId: '', // 编制依据
      status: '', // 状态
      remark: '', // 预案简述
      commandList: [
        {id: 1, commandName: '总指挥', name: '', phone: '', position: [], departmentId: null},
        {id: 2, commandName: '副指挥', name: '', phone: '', position: [], departmentId: null},
      ], // 指挥部
      teamList: [], // 小组成员
      attachment: [], // 附件
      responsibility: '', // 主要职责
    }
  })

  const init = (id) => {
    
  }
  /** 应急工作组逻辑处理 - 开始 */
  const addCompanies = (type, titleType, index) => {
    personalDialogRef.value.init(type, titleType, index)
  }
  const personalChange = (data, type, index) => {
    console.log(data, type, index, 'personalChange');
    
    if(type === 1){
      const { id, name, phone, position, departmentId } = data
      
      formData.data.commandList[index].id = id
      formData.data.commandList[index].name = name
      formData.data.commandList[index].phone = phone
      formData.data.commandList[index].position = position
      formData.data.commandList[index].departmentId = departmentId
    }else{
      if(formData.data.teamList.length > 0) {
        let newData = formData.data.teamList.concat(data)
        // 使用 reduce 去重
        newData = newData.reduce((acc, cur) => {
          if (!acc.some(item => item.id === cur.id)) {
            acc.push(cur)
          }
          return acc
        }, [])
        formData.data.teamList = newData
      }else{
        formData.data.teamList = data
      }
    }

  }
  const companiesDel = async (index) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      formData.data.teamList.splice(index, 1)
    } catch {}

  } 
  /** 应急工作组逻辑处理 - 结束 */
  const closeForm = () => {
    // 关闭表单弹窗逻辑
    goBack()
  }
  const submitForm = () => {
    const formEl = formRef.value
    console.log(formEl, 'formEl');
    if (!formEl) return
    formEl.validate((valid, fields) => {
      if (valid) {

        console.log(formData.data, valid, '走这里来了？？？');
      }else{
        for(let key in fields){
          message.error(fields[key][0].message)
        }
      }
    })
  }
  defineExpose({ init })
</script>
<style lang="scss" scoped>
.content{
    width: 100%;
    min-height: 80px;
    padding: 6px;
    margin-bottom: 24px;
    // border-right: 1px solid #eee;
    box-sizing: border-box;
    .content_head {
        margin-bottom: 24px;
        .line {
            width: 5px;
            height: 21px;
            background: #50B5FF;
        }
        .title {
            font-size: 18px;
            color: #333;
            margin-left: 12px;
            font-weight: 600;
        }
    }
    .content_main {
        width: 100%;
        padding: 0 32px;
        box-sizing: border-box;
    }
}
::v-deep .el-form-item{
  width: 100%;
}
.coord{
  height: 32px;
  box-sizing: border-box;
  padding: 4px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  color: #636660;
  &:hover{
    border-color: #bcbdc0;
  }
}
.cursor_pointer{
  &:hover{
    border-color: rgb(64, 158, 255);
  }
}
.formInp{
  width: 100%;
}
.addRow{
  margin-top: 12px;
  width: 100%;
}
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
::v-deep .el-upload-list.el-upload-list--text{
  overflow-y: scroll;
  height: 120px;
}
</style>
